import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-06-05
 * Time: 14:59
 */

class User{
    public String name;
    public String password;

    public User() {

    }

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }
}
class Avatar {
    public String name;
    public String fileName;

    public Avatar() {
    }

    public Avatar(String name, String fileName) {
        this.name = name;
        this.fileName = fileName;
    }
}


@WebServlet("/login")
public class LogIn extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        resp.setContentType("text/html; charset=utf8");
        if(session == null) {//不存在这条记录
            resp.getWriter().write("No");
            return;
        }
        String username = (String)session.getAttribute("username");
        if(username == null) {
            resp.getWriter().write("No");
            //虽然有session，但是没有对应的属性，为登录状态异常
            //本程序里不会出现~
            //因为登录的时候只有登录成功才会把这个设置这个username
            return;
        }
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/Loves?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("mmsszsd666");//这是俺的微信号，欢迎添加，相互学习！
        try {
            Connection connection = dataSource.getConnection();
            String sql = "select * from image where name = '" + username  + "';";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            //这里的Set并不是，对象为Love的Set集合，而是一个迭代器！
            ResultSet set = preparedStatement.executeQuery();
            //迭代他（是next方法而不是hasNext）
            if(set.next()) {
                String json = objectMapper.writeValueAsString(new Avatar(username, set.getString("fileName")));
                resp.setContentType("application/json; charset=utf8");
                resp.getWriter().write(json);
            }else {
                resp.getWriter().write("NoImage");
            }
            set.close();
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取客户端发来的请求
     * 1. 输入后，发送请求给服务器
     * 2. 服务器在session中判断其数据的正确性
     *         1. 不正确，在登录页面alert错误
     *         2. 正确，返回表白墙主页（用户页面设计暂不处理），alert一下登录成功（动态性）
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(true);
        resp.setContentType("text/html; charset=utf8");
        User user = objectMapper.readValue(req.getInputStream(), User.class);
        String username = "'" + user.name + "'";//获取key对应值
        String password = "'" + user.password + "'";

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/Loves?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("mmsszsd666");//这是俺的微信号，欢迎添加，相互学习！
        try {
            Connection connection = dataSource.getConnection();
            String sql = "select * from users where name = " + username + "and password = " + password + ";";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            //这里的Set并不是，对象为Love的Set集合，而是一个迭代器！
            ResultSet set = preparedStatement.executeQuery();
            //迭代他（是next方法而不是hasNext）
            if(set.next()) {
                //有这个用户,如果没有这个会话
                session.setAttribute("username", user.name);
                resp.getWriter().write("欢迎[" + username + "]！");
            }else {
                resp.getWriter().write("No");
            }
            set.close();
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }



    }
}
